package com.xk.meeting.controller;

import com.xk.meeting.entity.User;
import com.xk.meeting.service.UserService;
import com.xk.meeting.service.UserServiceImpl;
import com.xk.meeting.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/autoLogin")
public class AutoLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");

        Cookie[] cookies = request.getCookies();
        String username = null;
        String ssid = null;
        for (Cookie cookie : cookies){
            if(cookie.getName().equals("userKey")){
                username = cookie.getValue();
            }
            if(cookie.getName().equals("ssid")){
                ssid = cookie.getValue();
            }
        }
        if(username != null && ssid != null && ssid.equals(CookieUtils.md5Encrypt(username))){
                UserService userService = new UserServiceImpl();
                User user = userService.getUserForPhone(username);
                HttpSession session = request.getSession();
                session.setAttribute("user",user);
//                response.sendRedirect("index.jsp");
        }/*else {
//            response.sendRedirect("index.jsp");
        }*/
    }
}
